package com.mrd.framework.security.config;

import com.mrd.framework.config.web.json.Result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 统一异常处理 Created by winaya on 2016/12/9.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 全局异常处理
     *
     * @param model model
     * @param e     异常
     * @return 异常页面
     */
    @ExceptionHandler(value = Exception.class)
    public String defaultExceptionHandler(Model model, Exception e) {
        logger.error("捕获了异常!", e);
        e.printStackTrace();
        return "/404";
    }

    /**
     * 上传文件超过限制的错误
     */
    private static final String FILE_OUT_OF_SIZE_EXCEPTION_MESSAGE = "The field attach exceeds its maximum permitted size of \\d+ bytes";
    private static final Pattern FILE_OUT_OF_SIZE_PATTERN = Pattern.compile(FILE_OUT_OF_SIZE_EXCEPTION_MESSAGE);
    @Value("${multipart.max-file-size}")
    private String fileSize;

    /**
     * 上传错误处理
     */
    @ExceptionHandler(value = MultipartException.class)
    @ResponseBody
    public Result uploadExceptionHandler(Model model, MultipartException e) {
        String message = e.getMessage();
        Matcher matcher = FILE_OUT_OF_SIZE_PATTERN.matcher(message);
        if (matcher.find()) {
            return Result.newFailInstance("文件上传失败!<br/>上传文件不允许超过" + fileSize + "!");
        }
        return null;
    }
}
